<template>
  <view class="chart_detail">
    <view class="header">
      <view class="header_box">
        <view class="header_item header_top">
          <view class="left">{{ navTitle + "-统计" }}</view>
          <view class="right" @click="changePart">
            <image src="/static/images/index/change.svg" mode="" />
            切换</view
          >
        </view>
      </view>

      <view class="header_box">
        <view class="header_item header_middle">
          <view class="dateLabel">日期范围:</view>
          <view class="dateContent" @click="showFilerTime">
            <view
              class="dateStr"
              :style="{ color: filter.dateType == 0 ? '#999' : '' }"
            >
              {{
                filter.dateType != 4
                  ? ["选择日期", "今天", "近7天", "近30天"][
                      `${filter.dateType}`
                    ]
                  : `${filter.startTime.replaceAll('/','-')}至${filter.endTime.replaceAll('/','-')}`
              }}
            </view>
            <view class="right">
              <uni-icons size="14" color="#999" type="arrowright"></uni-icons>
            </view>
          </view>
        </view>
      </view>
      <view class="header_box">
        <view class="header_item statusList">
          <view
            :class="['status_item', item.val == statusActive ? 'active' : '']"
            v-for="(item, index) in statusList"
            :key="index"
            @click="chooseStatus(item)"
            >{{ item.name }}</view
          >
        </view>
      </view>
      <view class="totalList" v-if="type == 1">
        <view class="total_item">
          共<text>{{ buildingTotal }} <text class="line"></text> </text>个项目
        </view>
        <view class="total_item">
          <text>{{ elevatorTotal }}</text>
          台电梯
          <text class="line"></text>
        </view>
        <view class="total_item">
          <text>{{ planTotal }}</text>
          个任务
        </view>
      </view>
      <view class="totalList" v-else>
        <view class="total_item">
          共<text>{{ buildingTotal }}</text>
          <text class="line"></text>
          个项目
        </view>
        <view class="total_item">
          <text>{{ elevatorTotal }}</text>
          台电梯
        </view>
      </view>
    </view>
    <scroll-view
      scroll-y="true"
      @scrolltolower="scrolltolower"
      :style="{
        paddingBottom: `${safeAreaBottom}px`,
        height: windowHeight - 152 - safeAreaBottom+ 'px',
      }"
    >
      <view class="content">
        <view class="list" v-if="list.length">
          <list-card
            v-for="(item, index) in list"
            :key="index"
            :cardType="type"
            :msg="item"
          ></list-card>
        </view>
        <default-block v-else></default-block>
      </view>
    </scroll-view>

    <repairtimeFilter
      ref="aa"
      @closeTimeFilter="closeTimeFilter"
    ></repairtimeFilter>
  </view>
</template>

<script>
import listCard from './components/listCard.vue';
import defaultBlock from '../../components/default/default.vue';
import repairtimeFilter from './components/timeFilter.vue';
import {
	getRepetitionDetail,
	getRepetitionCount,
	getStatusCount,
	getStatusDetail,
} from '@/apis/statistic.js';
export default {
	components: {
		listCard,
		defaultBlock,
		repairtimeFilter,
	},
	onLoad(e) {
		uni.getSystemInfo({
			success: (res) => {
				console.log(res);
				this.windowHeight = res.windowHeight;
				this.safeAreaBottom = res.screenHeight - res.safeArea.bottom;
			},
		});
		this.type = e.type;
		uni.setNavigationBarTitle({
			title: this.type == 1 ? '电梯维修任务明细' : '电梯明细',
		});
		this.statusList =
      e.type == 1
      	? [
      		{ name: '全部', val: 0 },
      		{ name: '待开始', val: 2 },
      		{ name: '维修中', val: 3 },
      		{ name: '已完成', val: 4 },
      	]
      	: [
      		{ name: '全部', val: 0 },
      		{ name: '正常梯', val: 1 },
      		{ name: '重复故障梯', val: 2 },
      		{ name: '非重复故障梯', val: 3 },
      	];
		this.filter.dateType = e.dateType;
		this.filter.startTime = e.startTime;
		this.filter.endTime = e.endTime;
		uni.getStorage({
			key: 'repairStatistical',
			success: (res) => {
				console.log('修改数据源-维修', res);
				if (res.data.isFirst || res.data.id.length == 0) {
					this.navTitle = res.data.allGroupTitles[0] + '整体';
				} else {
					this.navTitle =
            res.data.title.length == 1
            	? res.data.title[0]
            	: `已选${res.data.title.length}部门`;
				}
				this.deptIds = res.data.id.length == 0 ? res.data.allGroupIds : res.data.id;
			},
		});
	},
	onShow() {
		uni.getStorage({
			key: 'repairStatistical',
			success: (res) => {
				console.log('修改数据源-维修', res);
				if (res.data.isFirst || res.data.id.length == 0) {
					this.navTitle = res.data.allGroupTitles[0] + '整体';
				} else {
					this.navTitle =
            res.data.title.length == 1
            	? res.data.title[0]
            	: `已选${res.data.title.length}部门`;
				}
				this.deptIds = res.data.id.length == 0 ? res.data.allGroupIds : res.data.id;
				if (this.type == 1) {
					this.fetchStatusPage();
				} else {
					this.fetchRepetitionPage();
				}
			},
		});
	},
	data() {
		return {
			type: '',
			navTitle: '',
			statusList: [
				{ name: '全部', val: 0 },
				{ name: '待开始', val: 2 },
				{ name: '维修中', val: 3 },
				{ name: '已完成', val: 4 },
			],
			statusActive: 0,
			safeAreaBottom: '',
			list: [], // 获取数据
			newsList: [], // 处理分页数据
			filter: {
				dateType: '',
				startTime: '',
				endTime: '',
			},
			deptIds: [],
			buildingTotal: 0,
			elevatorTotal: 0,
			planTotal: 0,
			page: {
				size: 10,
				current: 1,
			},
			windowHeight: 0,
			isLoadMore: false,
		};
	},
	methods: {
		scrolltoupper() {
			console.log('触顶');
			if (this.type == 1) {
				this.page.current = 1;
				this.list = [];
				this.fetchStatusDetail();
			} else {
				this.page.current = 1;
				this.list = [];
				this.fetchRepetitionDetail();
			}
		},
		scrolltolower() {
			// console.log("底部时间");
			if (!this.isLoadMore) {
				// 此处判断，上锁，防止重复请求
				this.isLoadMore = true;
				this.page.current += 1;
				if (this.type == 1) {
				} else {
					this.fetchRepetitionDetail();
				}
			}
		},
		// 请求任务状态
		async fetchStatusPage() {
			await this.fetchStatusCount();
			await this.fetchStatusDetail();
		},
		// 请求任务状态统计
		fetchStatusCount() {
			const { startTime, endTime } = this.filter;
			return new Promise((resolve) => {
				getStatusCount({
					deptIds: this.deptIds,
					planStatus: this.statusActive,
					startDate: startTime,
					endDate: endTime,
					...this.page,
				}).then((res) => {
					console.log(res, '');
					this.buildingTotal = res.data.buildingTotal;
					this.elevatorTotal = res.data.elevatorTotal;
					this.planTotal = res.data.planTotal;
					if (res) {
						resolve({});
					}
				});
			});
		},
		// 请求任务状态列表
		fetchStatusDetail() {
			uni.showLoading({
				icon: 'none',
				title: '加载中',
				mask: true,
			});
			const { startTime, endTime } = this.filter;
			this.list = [];
			return new Promise((resolve) => {
				getStatusDetail({
					deptIds: this.deptIds,
					planStatus: this.statusActive,
					startDate: startTime,
					endDate: endTime,
					...this.page,
				}).then((res) => {
					// console.log(res, res.data.records, "重复梯列表");
					if (res) {
						// this.list = res.data.records;
						this.list = this.list.concat(res.data.records);
						if (res.data.records.length < this.page.size) {
							this.isLoadMore = true;
						} else {
							this.isLoadMore = false;
						}
						uni.hideLoading();
						resolve({});
					} else {
						uni.showToast({ title: '请求失败', icon: 'none' });
						this.isLoadMore = false;
						if (this.page.current > 1) {
							this.page.current -= 1;
						}
					}
				});
			});
		},

		// 请求重复梯
		async fetchRepetitionPage() {
			await this.fetchRepetitionCount();
			await this.fetchRepetitionDetail();
		},
		// 重复梯统计
		fetchRepetitionCount() {
			const { startTime, endTime } = this.filter;
			this.list = [];
			return new Promise((resolve) => {
				getRepetitionCount({
					deptIds: this.deptIds,
					temp: this.statusActive,
					startDate: startTime,
					endDate: endTime,
					...this.page,
				}).then((res) => {
					console.log(res, '重复梯统计');
					this.buildingTotal = res.data.buildingTotal;
					this.elevatorTotal = res.data.elevatorTotal;
					if (res) {
						resolve({});
					}
				});
			});
		},
		// 重复梯列表
		fetchRepetitionDetail() {
			uni.showLoading({
				icon: 'none',
				title: '加载中',
				mask: true,
			});
			const { startTime, endTime } = this.filter;
			return new Promise((resolve) => {
				getRepetitionDetail({
					deptIds: this.deptIds,
					temp: this.statusActive,
					startDate: startTime,
					endDate: endTime,
					...this.page,
				}).then((res) => {
					console.log(res, res.data.records, '重复梯列表');
					if (res) {
						// this.list = res.data.records;
						this.list = this.list.concat(res.data.records);
						if (res.data.records.length < this.page.size) {
							this.isLoadMore = true;
						} else {
							this.isLoadMore = false;
						}
						uni.hideLoading();
						resolve({});
					} else {
						uni.showToast({ title: '请求失败', icon: 'none' });
						this.isLoadMore = false;
						if (this.page.current > 1) {
							this.page.current -= 1;
						}
					}
				});
			});
		},
		chooseStatus(item) {
			this.statusActive = item.val;
			if (this.type == 1) {
				this.fetchStatusPage();
			} else {
				this.fetchRepetitionPage();
			}
		},
		showFilerTime() {
			console.log(this.$refs.aa);
			this.$refs.aa.initData(this.filter);
		},
		closeTimeFilter(res) {
			console.log(res, 888);
			if (res.dateType == 0) {
				this.filter.startTime = '';
				this.filter.endTime = '';
				this.filter.dateType = 0;
			} else {
				this.filter = res;
			}

			if (this.type == 1) {
				this.fetchStatusPage();
			} else {
				this.fetchRepetitionPage();
			}
		},
		changePart() {
			uni.navigateTo({
				url: '/subpages/statistics/partSelect',
			});
		},
	},
};
</script>
<style lang="scss">
page {
  background: #f3f6f8;
}
</style>
<style lang="scss" scoped>
.chart_detail {
  .header {
    background: #fff;
    position: sticky;
    top: 0;
    left: 0;
    z-index: 99;
    .header_box {
      border-bottom: 2rpx solid #eee;
      .header_item {
        padding: 16rpx 20rpx;
        display: flex;
      }
      .header_middle,
      .header_top {
        justify-content: space-between;
        align-items: center;
        .left {
          font-size: 32rpx;
          color: #333;
          font-weight: 500;
          border-left: 4rpx solid #0091ff;
          padding-left: 16rpx;
        }
        .right {
          color: #0091ff;
          font-weight: 400;
          font-size: 24rpx;
          display: flex;
          align-items: center;
          image {
            width: 32rpx;
            height: 32rpx;
            margin-top: 6rpx;
            margin-right: 4rpx;
          }
        }
        .dateLabel {
          display: flex;
          flex: 1;
          font-size: 26rpx;
          color: #666;
        }
        .dateContent {
          width: 568rpx;
          height: 48rpx;
          background: #f3f6f8;
          border-radius: 8rpx;
          font-size: 24rpx;
          color: #333;
          display: flex;
          align-items: center;
          justify-content: center;
          .dateStr {
            display: flex;
            flex: 1;
            justify-content: center;
          }
          .right {
            display: flex;
            width: 32rpx;
            padding-right: 8rpx;
            justify-content: flex-end;
          }
        }
      }
      .status_item {
        padding: 6rpx 20rpx;
        background: #f3f6f8;
        border-radius: 22rpx;
        color: #666;
        font-size: 26rpx;
        margin-right: 16rpx;
      }
      .active {
        font-size: 26rpx;
        color: #0091ff;
        background: #dcf0ff;
      }
    }
    .totalList {
      display: flex;
      padding: 16rpx 20rpx;
      background: #f3f6f8;
      .total_item {
        height: 34rpx;
        font-size: 24rpx;
        color: #999;
        position: relative;
        padding-right: 20rpx;
        align-items: center;
        .line {
          position: absolute;
          right: 10rpx;
          top: 6rpx;
          width: 2rpx;
          height: 24rpx;
          background: #cccccc;
        }
      }
      text {
        color: #0091ff;
      }
    }
  }
  .content {
    padding: 0 20rpx;
  }
}
</style>
